#ifndef __UIMARKUP_H__
#define __UIMARKUP_H__

#pragma once

namespace uilib {

enum
{
    XMLFILE_ENCODING_UTF8 = 0,
};

class CMarkup;
class CMarkupNode;


class CMarkup
{
    friend class CMarkupNode;
public:
    CMarkup(LPSTRING pstrXML = NULL);
    ~CMarkup();

    int Load(LPSTRING pstrXML);
    int LoadFromMem(BYTE* pByte, DWORD dwSize, int encoding = XMLFILE_ENCODING_UTF8);
    int LoadFromFile(LPSTRING pstrFilename, int encoding = XMLFILE_ENCODING_UTF8);
    void Release();
	int IsValid() const;

    void SetPreserveWhitespace(bool bPreserve = true);
    CMarkupNode GetRoot();

private:
    typedef struct tagXMLELEMENT
    {
        ULONG iStart;
        ULONG iChild;
        ULONG iNext;
        ULONG iParent;
        ULONG iData;
    } XMLELEMENT;

    LPTSTR m_pstrXML;
    XMLELEMENT* m_pElements;
    ULONG m_nElements;
    ULONG m_nReservedElements;
    bool m_bPreserveWhitespace;

private:
    bool _Parse();
    bool _Parse(LPTSTR& pstrText, ULONG iParent);
    XMLELEMENT* _ReserveElement();
    inline void _SkipWhitespace(LPTSTR& pstr) const;
    inline void _SkipWhitespace(LPSTRING& pstr) const;
    inline void _SkipIdentifier(LPTSTR& pstr) const;
    inline void _SkipIdentifier(LPSTRING& pstr) const;
    bool _ParseData(LPTSTR& pstrText, LPTSTR& pstrData, char cEnd);
    void _ParseMetaChar(LPTSTR& pstrText, LPTSTR& pstrDest);
    bool _ParseAttributes(LPTSTR& pstrText);
};


class CMarkupNode
{
    friend class CMarkup;
private:
    CMarkupNode();
    CMarkupNode(CMarkup* pOwner, int iPos);

public:
    bool IsValid() const;

    CMarkupNode GetParent();
    CMarkupNode GetSibling();
    CMarkupNode GetChild();
    CMarkupNode GetChild(LPSTRING pstrName);

    bool HasSiblings() const;
    bool HasChildren() const;
    LPSTRING GetName() const;
    LPSTRING GetValue() const;

    bool HasAttributes();
    bool HasAttribute(LPSTRING pstrName);
    int GetAttributeCount();
    LPSTRING GetAttributeName(int iIndex);
    LPSTRING GetAttributeValue(int iIndex);
    LPSTRING GetAttributeValue(LPSTRING pstrName);
    bool GetAttributeValue(int iIndex, LPTSTR pstrValue, SIZE_T cchMax);
    bool GetAttributeValue(LPSTRING pstrName, LPTSTR pstrValue, SIZE_T cchMax);

private:
    void _MapAttributes();

    enum { MAX_XML_ATTRIBUTES = 64 };

    typedef struct
    {
        ULONG iName;
        ULONG iValue;
    } XMLATTRIBUTE;

    int m_iPos;
    int m_nAttributes;
    XMLATTRIBUTE m_aAttributes[MAX_XML_ATTRIBUTES];
    CMarkup* m_pOwner;
};

} // namespace DuiLib

#endif // __UIMARKUP_H__
